package com.zm.controller;

import com.zm.bean.HeartBeatBean;
import com.zm.bean.OutHeartBean;
import com.zm.bean.TestDoorRecordBean;
import com.zm.service.CabHeartBeatDataService;
import com.zm.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping(value = "/heartBeat", produces = {"application/json;charset=UTF-8"})
public class CabHeartBeatController {
    SimpleDateFormat ymdhmsFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    SimpleDateFormat ymdFormat = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat ymFormat = new SimpleDateFormat("yyyyMM");

    @Autowired
    private CabHeartBeatDataService mService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {

        return "heartBeatIndex";
    }

    @RequestMapping(value = "/heartBeat", method = RequestMethod.GET)
    public String showAllByCabinetId() {

        return "heartBeatIndex";
    }

    @RequestMapping(value = "/show", method = RequestMethod.GET)
    public String showAllByCabinetId(ModelMap modelMap,
                                     @RequestParam(required = false) String cid,
                                     @RequestParam(required = false) String date,
                                     @RequestParam(required = false, defaultValue = "1") int curPage,
                                     @RequestParam(required = false, defaultValue = "100") int pageCount,
                                     @RequestParam(required = false, defaultValue = "100") int pageSize,
                                     @RequestParam(required = false, defaultValue = "0") int doorNo,
                                     @RequestParam(required = false, defaultValue = "") String format

    ) {

        List<HeartBeatBean> mBeans;
        int totalElements = 0; //总条数
        int totalPages = 0; // 总页数
        Page<TestDoorRecordBean> pageRecords;

        String dateYm = "";
        Date tempDate = null;
        if (date == null) {
            date = ymdFormat.format(new Date());
        }

        try {
            tempDate = ymdFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (tempDate != null) {
            dateYm = ymFormat.format(tempDate);
        }

        String start = date + " 00:00:00";
        String end = date + " 23:59:59";
        long startLong = 0, endLong = 0;

        try {
            startLong = ymdhmsFormat.parse(start).getTime() / 1000;
            endLong = ymdhmsFormat.parse(end).getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (startLong == 0 || endLong == 0) {
            return "时间异常";
        }

        String collectionName = "cd_battery_" + dateYm;

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(curPage, pageSize, sort);

        if (cid == null) {
            modelMap.addAttribute("cabinetId", "全部");
            mBeans = mService.findAllByCabinet(collectionName, date, cid, startLong, endLong);
        } else {
            modelMap.addAttribute("cabinetId", cid);
            mBeans = mService.findAllByCabinet(collectionName, date, cid, startLong, endLong);
        }

        System.out.println(" mBeans.size()=" + mBeans.size());

        List<OutHeartBean> outList = getOutList(mBeans);

        System.out.println("outList.size()=" + outList.size());

//        if (format.equals("json")) {
//            echo json_encode ($log);
//        } else {
//            $this -> printLog($log, '电柜日志: '.$cabinet);
//        }

        modelMap.addAttribute("outList", outList);
        modelMap.addAttribute("maxLastNum", maxLastNum);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("pageSize", pageSize);

        return "showHeartBeat";
    }

    int maxLastNum = 0;

    @RequestMapping(value = "/showFindBId", method = RequestMethod.GET)
    public String showFindBId(ModelMap modelMap,
                              @RequestParam(required = false) String bid,
                              @RequestParam(required = false) String date,
                              @RequestParam(required = false, defaultValue = "100") int limit,
                              @RequestParam(required = false, defaultValue = "1") int curPage,
                              @RequestParam(required = false, defaultValue = "100") int pageCount,
                              @RequestParam(required = false, defaultValue = "100") int pageSize,
                              @RequestParam(required = false, defaultValue = "0") int doorNo,
                              @RequestParam(required = false, defaultValue = "") String format

    ) {

        if (bid == null) {
            return "请输入电池编号";
        }


        List<HeartBeatBean> mBeans;
        int totalElements = 0; //总条数
        int totalPages = 0; // 总页数
        Page<TestDoorRecordBean> pageRecords;

        String dateYm = "";
        Date tempDate = null;
        if (date == null) {
            date = ymdFormat.format(new Date());
        }

        try {
            tempDate = ymdFormat.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (tempDate != null) {
            dateYm = ymFormat.format(tempDate);
        }

        String start = date + " 00:00:00";
        String end = date + " 23:59:59";
        long startLong = 0, endLong = 0;

        try {
            startLong = ymdhmsFormat.parse(start).getTime() / 1000;
            endLong = ymdhmsFormat.parse(end).getTime() / 1000;
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (startLong == 0 || endLong == 0) {
            return "时间异常";
        }

        String collectionName = "cd_battery_" + dateYm;

        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Pageable pageable = PageRequest.of(curPage, pageSize, sort);

        modelMap.addAttribute("bid", bid);
        mBeans = mService.findAllByBid(collectionName, date, bid, limit);

        System.out.println(" mBeans.size()=" + mBeans.size());
        List<OutHeartBean> outList = getOutList(mBeans);

        modelMap.addAttribute("outList", outList);
        modelMap.addAttribute("limit", limit);
        modelMap.addAttribute("maxLastNum", 1);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("pageSize", pageSize);

        return "showHeartBeatBid";
    }


    public List<OutHeartBean> getOutList(List<HeartBeatBean> mBeans) {
        int group = 0;
        int num = 0, lastNum = 0;
        long lastUpdateTime = 0;
//        $log = array();
        int status = 0;//0：正常、1：多电池、-1：丢电池
        List<OutHeartBean> outList = new ArrayList<>();
        List<HeartBeatBean> tmpArr = new ArrayList<>();

        HeartBeatBean heartBeatBean;
        for (int i = 0; i < mBeans.size(); i++) {
            heartBeatBean = mBeans.get(i);
            //验证数据格式
//            if (StringUtil.bidIsEmpty(heartBeatBean.battery) || heartBeatBean.door < 0) {
//                continue;
//            }
//如果是仓门筛选
//            if (doorNo > 0 && heartBeatBean.door != doorNo) {
//                continue;
//            }

            //总结包信息
            if (heartBeatBean.time - lastUpdateTime > 0) {
                //新包
                group++;


                //判断丢吞电池
                if ((num < lastNum) && (group > 1)) { //丢电池
                    status = -1;
                } else if ((num > lastNum) && (group > 2)) { //吞电池
                    status = 1;
                } else {
                    status = 0;
                }

                //压包
                if (group > 1) {
                    OutHeartBean outHeartBean = new OutHeartBean();
                    outHeartBean.group = group;
                    outHeartBean.num = lastNum;

                    outHeartBean.status = status;
                    outHeartBean.time = lastUpdateTime;
                    outHeartBean.heartList = tmpArr;
                    outList.add(outHeartBean);
//                    $log[] = ['info' =>$tmpArr, 'status' =>$status];
                    tmpArr = new ArrayList<>();
                }

                lastNum = num;
                lastUpdateTime = heartBeatBean.time;
                num = 0;
            }

            tmpArr.add(heartBeatBean);

            if (!StringUtil.bidIsEmpty(heartBeatBean)) {
                num++;
            }

        }

        OutHeartBean lastOutBean = null, nowOutBean = null;
        int batNum = 0, lastBatNum = 0;
        int emptyNum = 0, lastEmptyNum = 0;
        long time = 0, lastTime = 0;

        for (int i = 1; i < outList.size(); i++) {
            lastOutBean = outList.get(i - 1);
            nowOutBean = outList.get(i);
            List<HeartBeatBean> lastHeartList = lastOutBean.heartList;

            for (int h = 0; h < lastHeartList.size(); h++) {
                HeartBeatBean innerHeartBean = lastHeartList.get(h);
                if (StringUtil.bidIsEmpty(innerHeartBean)) {
                    lastEmptyNum++;
                } else {
                    lastBatNum++;
                }

                if (lastTime != innerHeartBean.time) {
                    lastTime = innerHeartBean.time;
                }
            }

            nowOutBean.lastEmptyNum = lastEmptyNum;
            nowOutBean.lastBatNum = lastBatNum;
            nowOutBean.lastTime = lastTime;

            List<HeartBeatBean> nowHeartList = nowOutBean.heartList;

            for (HeartBeatBean nowHeart : nowHeartList) {
                if (StringUtil.bidIsEmpty(nowHeart)) {
                    emptyNum++;
                } else {
                    batNum++;
                }

                if (time != nowHeart.time) {
                    time = nowHeart.time;
                }
            }

            if (maxLastNum < (emptyNum + batNum)) {
                maxLastNum = (emptyNum + batNum);
            }

            nowOutBean.thisBatNum = batNum;
            nowOutBean.thisEmptyNum = emptyNum;
            nowOutBean.thisTime = time;

            outList.set(i, nowOutBean);
            lastEmptyNum = 0;
            lastBatNum = 0;
            emptyNum = 0;
            batNum = 0;
        }
        return outList;
    }


}
